<?php
/**
 * 用户模块
 * @author SongKejing
 *
 */
class UserModel extends BaseModel{
	
	/**
	 * 用户登录
	 * @param string $name
	 * @param string $psw
	 */
	public function userLogin($name, $psw){
		if (isset($_SESSION['uid']) && !empty($_SESSION['uid'])){
			return $this->getUserNavigation($_SESSION['uid']);
		}
		$sql = "SELECT * FROM t_user WHERE name='$name' AND is_valid=1 LIMIT 1";
		$result = $this->DBSelect($sql);
		if (empty($result)){
			return FALSE;
		}
		if ($psw!=$result[0]['psw']){
			return FALSE;
		}
		//用户uid和name写入到session
		$_SESSION['uid'] = $result[0]['user_id'];
		$_SESSION['name'] = $result[0]['name'];
		return TRUE;
	}
	
	/**
	 * 获取用户权限
	 * @param int $uid
	 */
	public function getUserPowers($uid){
		if (empty($uid)){
			return FALSE;
		}
		if (isset($_SESSION['powers'])){
			return json_decode($_SESSION['powers'], true);
		}
		//查询用户权限
		$sql = "SELECT DISTINCT p.power_id, p.power_name, p.power_url, p.father_id, p.img_url, p.sort_id from t_power p, t_role_power r_p, t_user_role u_r 
		WHERE p.power_id=r_p.power_id AND p.is_valid=1 AND r_p.role_id=u_r.role_id AND u_r.user_id='$uid' ORDER BY p.power_id ASC";
		$powers = $this->DBSelect($sql);
		if (empty($powers)){
			return FALSE;
		}
		$_SESSION['powers'] = json_encode($powers);		
		return $powers;		
	}
	
	/**
	 * 获取用户导航条信息
	 * @param int $uid
	 * @return array
	 */
	public function getUserNavigation($uid){
		if (empty($uid)){
			return FALSE;
		}
		if(isset($_SESSION['navi']) && !empty($_SESSION['navi'])){
			return json_decode($_SESSION['navi'], true);
		}
		$powers = $this->getUserPowers($uid);
		$return_array = array();
		//获取所有的father_id
		$father_ids_array = array();
		foreach ($powers as $power_each){
			$father_ids_array[] = $power_each['father_id'];
		}
		$father_ids_array = array_unique($father_ids_array);
		sort($father_ids_array);
		foreach ($father_ids_array as $father_id_each){
			$son = $this->getPowersByFatherID($powers, $father_id_each);
			$return_array = $this->appendUserPowers($return_array, $son, $father_id_each);		
		}
		$_SESSION['navi'] = json_encode($return_array);
		return $return_array;	
	}
	
	
	/**
	 * 拼接权限数组，目前支持三级菜单
	 * @param array $power_array
	 * @param array $son_power_array
	 * @param int $father_id
	 */
	private function appendUserPowers($power_array, $son_power_array, $father_id=0){
		if (empty($son_power_array)){
			return $power_array;
		}
		if (empty($power_array)){
			foreach ($son_power_array as $son_power_each){				
				$power_array[$son_power_each['sort_id']] = $son_power_each;
			}
		}else{
			foreach ($power_array as $power_key=>$power_each){
				if (isset($power_each['son']) && is_array($power_each['son'])){
					foreach ($power_each['son'] as $sub_power_key=>$sub_power_each){
						if ($sub_power_each['power_id']==$father_id){
							foreach ($son_power_array as $son_power_each){							
								$power_array[$power_key]['son'][$sub_power_key]['son'][$son_power_each['sort_id']] = $son_power_each;
							}
						}
					}
				}else{
					if ($power_each['power_id']==$father_id){
						foreach ($son_power_array as $son_power_each){							
							$power_array[$power_key]['son'][$son_power_each['sort_id']] = $son_power_each;
						}
					}
				}
			}
		}
		return $power_array;
	}
	
	/**
	 * 根据father_id获取权限
	 * @param array $powers
	 * @param int $father_id
	 */
	private function getPowersByFatherID($powers, $father_id){
		if (empty($powers) || !isset($father_id)){
			return FALSE;
		}
		$powers_array = array();
		foreach ($powers as $each){
			if ($each['father_id']==$father_id){
				$powers_array[] = $each;
			}
		}
		return $powers_array;		
	}
	
	/**
	 * 获取所有的订单数据
	 * @return array
	 */
	public function getAllOrderInfo(){
		$sql = "SELECT COUNT(OrderNumber) all_count, status FROM v1_order_status_history GROUP BY status";
		$order_his_count = $this->DBSelect($sql);
		$sql = "SELECT COUNT(OrderNumber) all_count, status FROM v1_order_status GROUP BY status";
		$order_count = $this->DBSelect($sql);
		foreach ($order_count as $order_count_each){
			foreach ($order_his_count as $key=>$order_his_count_each){
				if ($order_his_count_each['status']==$order_count_each['status']){
					$order_his_count[$key]['all_count'] = $order_his_count[$key]['all_count']+$order_count_each['all_count'];
				}
			}
		}
		return $this->tidyOrders($order_his_count);		
	}
	
	/**
	 * 获取今日订单
	 * @return array
	 */
	public function getTodayOrderInfo(){
		$today_zero_time = date('Y-m-d 00:00:00'); 
		$sql = "SELECT COUNT(OrderNumber) all_count, status FROM v1_order_status WHERE ctime>'$today_zero_time' GROUP BY status";
		return $this->tidyOrders($this->DBSelect($sql));
	}
	
	/**
	 * 依据订单status整理订单状态
	 * @param array $orders
	 * @return array(1=>已完成, 2=>'未完成')
	 */
	public function tidyOrders($orders){
		$return_array = array(
							1=>array(
								'all_count' => 0,
								'status' => 1,
							),
							2=>array(
								'all_count' => 0,
								'status' => 2,
							)
						);
		if(empty($orders)){
			return $return_array;
		}
		foreach($orders as $order_each){
			if ($order_each['status']==1){
				$return_array[1] = $order_each;
			}else{
				$return_array[2]['all_count'] = $return_array[2]['all_count']+$order_each['all_count'];
			}
		}
		return $return_array;
	}
	
	/**
	 * 获取用户信息
	 * @param int $uid
	 * @return array
	 */
	public function getUserInfo($uid=0){
		$user_id = $uid==0 ? $_SESSION['uid'] : $uid;
		$sql = "SELECT * FROM t_user WHERE user_id='$user_id' LIMIT 1";
		return $this->DBSelect($sql);
	}
	
	/**
	 * 更新用户资料
	 * @param string $name
	 * @param string $true_name
	 * @param string $email
	 * @param string $remark
	 * @param string $new_psw
	 * @param string $old_psw
	 * @return array
	 */
	public function updateUserInfo($name, $true_name, $email, $remark, $new_psw='', $old_psw='', $roles=array()){
		$uid = $_SESSION['uid'];
		//当原密码不为空时，验证密码
		if (!empty($old_psw)){
			$sql = "SELECT psw FROM t_user WHERE user_id='$uid' LIMIT 1";
			$psw = $this->DBSelect($sql);
			if ($psw[0]['psw']==$old_psw){
				$sql = "UPDATE t_user SET name='$name', true_name='$true_name', psw='$new_psw', email='$email', remark='$remark', update_time=CURRENT_TIMESTAMP() WHERE user_id='$uid'";
				if($this->DBUpdate($sql)){
					return array('result'=>TRUE, 'msg'=>'更新成功');
				}else{
					return array('result'=>FALSE, 'msg'=>'更新失败');
				}
			}else{
				return array('result'=>FALSE, 'msg'=>'旧密码错误');
			}
		}
		$sql = "UPDATE t_user SET name='$name', true_name='$true_name', email='$email', remark='$remark', update_time=CURRENT_TIMESTAMP() WHERE user_id='$uid'";
		if ($this->DBUpdate($sql)){
			//添加用户角色
			if(count($roles)>0){
				$sql = '';
				foreach ($roles as $role_each){
					if ($sql==''){
						$sql = "('$uid', $role_each)";
					}else{
						$sql .= ", ('$uid', $role_each)";
					}
				}
				//删除用户所有的角色
				$delete_sql = "DELETE FROM t_user_role WHERE user_id='$uid'";
				$this->DBDelete($delete_sql);
				//添加新角色
				$sql = "INSERT INTO t_user_role(user_id, role_id) VALUES".$sql;
				$newResult = $this->DBInsert($sql);
				if($newResult==FALSE){
					return array('result'=>false, 'msg'=>'修改用户角色失败！');
				}
			}		
			return array('result'=>TRUE, 'msg'=>'更新成功');
		}else{
			return array('result'=>FALSE, 'msg'=>'更新失败');
		}
	}
	
	/**
	 * 新增用户
	 * @param string $name
	 * @param string $true_name
	 * @param string $email
	 * @param string $remark
	 * @param string $psw
	 * @return array
	 */
	public function createUser($name, $true_name, $email, $remark, $psw){
		if (empty($name) || empty($psw)){
			return array('result'=>FALSE, 'msg'=>'用户名、密码不可为空！');
		}
		$sql = "INSERT INTO t_user(name, true_name, psw, email, remark, create_time, update_time) VALUES('$name', '$true_name', '$psw', '$email', '$remark', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP())";
		if($this->DBInsert($sql)){
			return array('result'=>TRUE, 'msg'=>'新建用户成功');
		}else{
			return array('result'=>FALSE, 'msg'=>'新建用户失败');
		}
	}
	
	/**
	 * 获取所有的用户
	 * @param int $current_page
	 * @param int $page_step
	 * @param int $page_count
	 * @return array
	 */
	public function getAllUsers($current_page=1, $page_step=12, $page_count=0){
		$begin = $page_step*($current_page-1);
		$sql = "SELECT * FROM t_user ORDER BY user_id ASC LIMIT $begin, $page_step";
		$users = $this->DBSelect($sql);
		foreach ($users as $key=>$user_each){
			$users[$key]['is_valid'] = ($user_each['is_valid']==1) ? '是' : '否';
			$each_roles = $this->getUserRoles($user_each['user_id']);
			$role_string = '';
			foreach ($each_roles['roles'] as $role_each){
				if($role_string==''){
					$role_string = $role_each['role_name'];
				}else{
					$role_string .= '，'.$role_each['role_name'];
				}
			}
			$users[$key]['role_string'] = $role_string;
		}
		if ($page_count==0){
			$sql = "SELECT COUNT(user_id) all_count FROM t_user";
			$page_count = $this->DBSelect($sql);
			$page_count = ceil($page_count[0]['all_count']/$page_step);
		}
		$page_array = array();
		for($i=1; $i<=$page_count; $i++){
			array_push($page_array, $i);
		}
		return array(
			'result'=>TRUE,
			'msg'=>'查询成功！',
			'page_count'=>$page_count,
			'page_step'=>$page_step,
			'current_page'=>$current_page,
			'page_array'=>$page_array,
			'users'=>$users,	
		);
	}
	
	/**
	 * 获取用户角色
	 * @param int $uid
	 * @return array
	 */
	public function getUserRoles($uid=0){		
		if($uid==0){			
			if(isset($_SESSION['roles'])){
				return json_decode($_SESSION['roles'], true);
			}
			$user_id = $_SESSION['uid'];
		}else {
			$user_id = $uid;
		}
		$sql = "SELECT r.role_id, r.role_name FROM t_role r, t_user_role u_r WHERE r.is_valid=1 AND r.role_id=u_r.role_id AND u_r.user_id='$user_id' ORDER BY r.role_id DESC";
		$roles = $this->DBSelect($sql);
		$roles_array = array(
							'roles'=>$roles
						);
		foreach ($roles as $role_each){
			$roles_array[$role_each['role_id']] = 'true';
		}
		if ($uid==0){
			$_SESSION['roles'] = json_encode($roles_array);
		}		
		return $roles_array;
	}
	
	/**
	 * 删除更新的用户
	 * @param int $uid
	 * @return array
	 */
	public function deleteModifyUserInfo($uid){
		$sql = "UPDATE t_user SET is_valid='2' WHERE user_id='$uid' LIMIT 1";
		if($this->DBUpdate($sql)){
			return array('result'=>true, 'msg'=>'删除成功！');
		}else{
			return array('result'=>false, 'msg'=>'删除失败！');
		}
	}
	
	/**
	 * 更新用户资料
	 * @param int $uid
	 * @param string $name
	 * @param string $true_name
	 * @param string $email
	 * @param string $remark
	 * @param string $psw
	 */
	public function updateModifyUserInfo($uid, $name, $true_name, $email, $remark, $psw='', $roles=array()){
		if(empty($psw)){
			$sql = "UPDATE t_user SET name='$name', true_name='$true_name', email='$email', remark='$remark', update_time=CURRENT_TIMESTAMP() WHERE user_id='$uid' LIMIT 1";
		}else{
			$sql = "UPDATE t_user SET name='$name', true_name='$true_name', email='$email', remark='$remark', psw='$psw', update_time=CURRENT_TIMESTAMP() WHERE user_id='$uid' LIMIT 1";
		}
		$update_result = $this->DBUpdate($sql);
		if($update_result==FALSE){
			return array('result'=>true, 'msg'=>'修改失败！');
		}else{			
			//添加用户角色
			if(count($roles)>0){
				$sql = '';
				foreach ($roles as $role_each){
					if ($sql==''){
						$sql = "('$uid', $role_each)";
					}else{
						$sql .= ", ('$uid', $role_each)";
					}
				}
				//删除用户所有的角色
				$delete_sql = "DELETE FROM t_user_role WHERE user_id='$uid'";
				$this->DBDelete($delete_sql);
				//添加新角色
				$sql = "INSERT INTO t_user_role(user_id, role_id) VALUES".$sql;
				$newResult = $this->DBInsert($sql);
				if($newResult==FALSE){
					return array('result'=>false, 'msg'=>'修改用户角色失败！');
				}
			}			
		}
		return array('result'=>true, 'msg'=>'修改成功！');
	}
	
	/**
	 * 新建用户
	 * @param string $name
	 * @param string $true_name
	 * @param string $psw
	 * @param string $email
	 * @param string $remark
	 * @param array $roles
	 * @return array
	 */
	public function newUser($name, $true_name, $psw, $email, $remark, $roles=array()){
		$sql = "SELECT user_id FROM t_user WHERE name='$name' LIMIT 1";
		$result = $this->DBSelect($sql);
		if(!empty($result)){
			return array('result'=>false, 'msg'=>'此用户名已经存在，请换用其他用户名！');
		}
		$create_id = $_SESSION['uid'];
		$sql = "INSERT INTO t_user(name, true_name, psw, email, remark, create_id, create_time) VALUES('$name', '$true_name', '$psw', '$email', '$remark', '$create_id', CURRENT_TIMESTAMP())";
		$newResult = $this->DBInsert($sql);
		if($newResult==FALSE){
			return array('result'=>true, 'msg'=>'新建用户失败！');
		}else{			
			$new_uid = $this->getLastInsID();
			//添加用户角色
			if(count($roles)>0){
				$sql = '';
				foreach ($roles as $role_each){
					if ($sql==''){
						$sql = "('$new_uid', $role_each)";
					}else{
						$sql .= ", ('$new_uid', $role_each)";
					}
				}
				//添加新角色
				$sql = "INSERT INTO t_user_role(user_id, role_id) VALUES".$sql;
				$newResult = $this->DBInsert($sql);
				if($newResult==FALSE){
					return array('result'=>false, 'msg'=>'新增用户角色失败！');
				}
			}			
			return array('result'=>true, 'msg'=>'新建用户成功！', 'uid'=>$new_uid);			
		}
	}		
}
?>